<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    @load="onLoad"
    :error.sync="error"
    error-text="请求失败，点击重新加载"
  >
    <CommentItem
      v-for="(comment, index) in list"
      :key="index"
      :comment="comment"
      @reply-click="$emit('reply-click', $event)"
    ></CommentItem>
    <!-- <van-cell
      v-for="(comment, index) in list"
      :key="index"
      :title="comment.content"
    /> -->
  </van-list>
</template>

<script>
import { getComment } from '@/api/comment.js'
import CommentItem from './comment-item.vue'
// console.log(getComment)
export default {
  name: 'CommentList',
  components: { CommentItem },
  props: {
    source: {
      type: [Number, String, Object],
      required: true,
    },
    // 将父组件传入的评论列表
    list: {
      type: Array,
      default: () => [],
    },
    // 接受父组件传入的type
    type: {
      type: String,
      // 自定义Prop数据验证
      validator(value) {
        // 只能传‘a'或者’c‘
        return ['a', 'c'].includes(value)
      },
      default: 'a',
    },
  },
  data() {
    return {
      // list: [],
      loading: false,
      finished: false,
      offset: null, // 加载下一页的页码值
      limit: 5, // 每页的数值
      error: false, // 默认加载失败
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    async onLoad() {
      // 1.调用接口
      try {
        const { data } = await getComment({
          type: this.type, // 对文章的评论传入a,对评论的回复传入c
          source: this.source, // 文章的id或者评论的id
          offset: this.offset, // 下一页的偏移值
          limit: this.limit, // 每一页的条数
        })
        console.log(data)
        // 2.得到数据追加到list
        const { results } = data.data
        this.list.push(...results)
        // 3.关闭loading状态
        this.loading = false
        // 4.判断数据是否加载完成  // 4.1已完成==》finished 设置为true
        if (results.length === 0) {
          this.finished = true
        } else {
          // 4.2未完成，更新下一页的页码值
          this.offset = data.data.last_id
        }
      } catch (err) {
        // 打开错误提示
        this.error = true
        // 关闭loading加载
        this.loading = false
      }
    },
  },
}
</script>

<style lang="less" scoped></style>
